package com.zydl.f9164m.home;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;


import com.clj.fastble.utils.BleLog;
import com.zydl.f9164m.R;
import com.zydl.f9164m.basis.Constants;
import com.zydl.f9164m.bean.DevTypeCfg;
import com.zydl.f9164m.eventbus.PopHandleMessage;
import com.zydl.f9164m.fragment.ApnFragment;
import com.zydl.f9164m.fragment.BeidouFragment;
import com.zydl.f9164m.fragment.CameraFragment;
import com.zydl.f9164m.fragment.CenterFragment;
import com.zydl.f9164m.fragment.EthernetFragment;
import com.zydl.f9164m.fragment.FlowFragment;
import com.zydl.f9164m.fragment.LoraFragment;
import com.zydl.f9164m.fragment.OutAndInFragment;
import com.zydl.f9164m.fragment.TerminalFragment;
import com.zydl.f9164m.fragment.passageway.PassagewayFragment;
import com.zydl.f9164m.fragment.sms.SMSFragment;
import com.zydl.f9164m.util.SoftKeyBoardListener;
import com.zydl.f9164m.util.SoftKeyInputHidWidget;
import com.zydl.f9164m.util.SubstringUtil;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;

import java.util.ArrayList;

import butterknife.BindView;
import my.BleUtils;
import my.MySharedPreferences;

/**
 * 首页
 */
public class HomeIndexActivity extends HomeBaseActivity implements HomeIndexView {

    @BindView(R.id.tablayout)
    SlidingTabLayout tablayout;

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private MyPagerAdapter mAdapter;

    @BindView(R.id.vp)
    ViewPager viewPager;

    TerminalFragment terminalFragment;
    CenterFragment centreFragment;
    FlowFragment flowFragment;
    OutAndInFragment outAndInFragment;
    //    ApnFragment apnFragment;
    CameraFragment cameraFragment;
    PassagewayFragment passagewayFragment;
    SMSFragment smsFragment;
    BeidouFragment beidouFragment;
    EthernetFragment ethernetFragment;
    LoraFragment loraFragment;

    MySharedPreferences mSp;

    private boolean isInitView = false;

    @Override
    public void initViews() {
//        setDefautTrans(false);
        super.initViews();
        setContentView(R.layout.home_index_activity);
        setTitle("参数设置");
        setTitleRightButton(R.mipmap.refresh, v -> refresh());
        //取消严格模式  FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        mSp = new MySharedPreferences(this);
        setView();

    }


    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        SoftKeyInputHidWidget.assistActivity(this);
        initAtShow();
    }


    public void refresh() {
        initAtShow();
    }


    private void initAtShow() {
        showLoading();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                BleUtils.sendAtShow(mContext,new BleUtils.BleUtilCallBack() {
                    @Override
                    public void onWriteFailure(String message) {
                        showToast(message);
                        dismissProgress();
                    }

                    @Override
                    public void onSuccess(String message) {
                        dismissProgress();
                        showToast(message);
                    }

                    @Override
                    public void onError(String message) {
                        showToast(message);
                        dismissProgress();
                    }

                    @Override
                    public void onResult(StringBuffer message) {
                        initLoraAndDeviceType(message.toString());
                        dismissProgress();
                    }

                    @Override
                    public void onByte(byte[] bytes) {

                    }
                });
            }
        }, 5000);   //5秒
    }

    public void initLoraAndDeviceType(String sMsgObjString) {
        if (!TextUtils.isEmpty(sMsgObjString)) {
            //版本号
            String lora = SubstringUtil.subString(sMsgObjString, "LORA ver:");
            mSp.putLora(lora);
            //当前连接的设备
            String device = SubstringUtil.subString(sMsgObjString, "Dev Type SHOW:");
            DevTypeCfg devTypeBean = new DevTypeCfg();
            if (TextUtils.isEmpty(device) || "数据异常，请重新获取".equals(device)) {
                mSp.putDevType("");
            } else {
                mSp.putDevType("" + devTypeBean.getDeviceName(Integer.valueOf(device)));
            }
        }

        if (!isInitView && !TextUtils.isEmpty(mSp.getDevType())) {
            isInitView = true;

            mFragments.add(terminalFragment);
            mTabEntities.add(new TabEntity("终端参数", 0, 0));

            mFragments.add(centreFragment);
            mTabEntities.add(new TabEntity("中心参数", 0, 0));

            mTabEntities.add(new TabEntity("导入导出", 0, 0));
            mFragments.add(outAndInFragment);

//            mFragments.add(apnFragment);
//            mTabEntities.add(new TabEntity("APN拨号", 0, 0));


            mFragments.add(cameraFragment);
            mTabEntities.add(new TabEntity("摄像头参数", 0, 0));

            mFragments.add(passagewayFragment);
            mTabEntities.add(new TabEntity("串口配置", 0, 0));

            mFragments.add(smsFragment);
            mTabEntities.add(new TabEntity("短信", 0, 0));

            mFragments.add(beidouFragment);
            mTabEntities.add(new TabEntity("北斗参数", 0, 0));
            mFragments.add(ethernetFragment);
            mTabEntities.add(new TabEntity("以太网参数", 0, 0));
//            mFragments.add(loraFragment);
//            mTabEntities.add(new TabEntity("LORA参数", 0, 0));

            mAdapter = new MyPagerAdapter(getSupportFragmentManager());
            viewPager.setAdapter(mAdapter);
            viewPager.setOffscreenPageLimit(mFragments.size());
            tablayout.setViewPager(viewPager);
            viewPager.setCurrentItem(0);
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    SoftKeyBoardListener.hideKeyboard(HomeIndexActivity.this);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }

        if (!TextUtils.isEmpty(mSp.getDevType())) {
            terminalFragment.setList(sMsgObjString.toString(), Constants.AT_FROM_DEVICE);
            centreFragment.setList(sMsgObjString.toString(), Constants.AT_FROM_DEVICE);
//            apnFragment.setList(sMsgObjString.toString(), Constants.AT_FROM_DEVICE);
            beidouFragment.setList(sMsgObjString.toString(), Constants.AT_FROM_DEVICE);
            ethernetFragment.setList(sMsgObjString.toString(), Constants.AT_FROM_DEVICE);
//            loraFragment.setList(sMsgObjString.toString(), Constants.AT_FROM_DEVICE);
            cameraFragment.setList(sMsgObjString.toString(), Constants.AT_FROM_DEVICE);
            passagewayFragment.setList(sMsgObjString.toString(), Constants.AT_FROM_DEVICE);
            smsFragment.setList(sMsgObjString.toString());
        }
    }

    @Override
    public void showAtShowString(String atShowString, int type) {
        terminalFragment.setList(atShowString, type);
        centreFragment.setList(atShowString, type);
//        apnFragment.setList(atShowString, type);
        beidouFragment.setList(atShowString, type);
        ethernetFragment.setList(atShowString, type);
//        loraFragment.setList(atShowString, type);
        cameraFragment.setList(atShowString, type);
        passagewayFragment.setList(atShowString, type);
        smsFragment.setList(atShowString);
        dismissProgress();
    }

    @Override
    public void showFail(String failMessage) {
        showToast(failMessage);
        dismissProgress();
    }


    private void setView() {
        terminalFragment = TerminalFragment.newInstance();
        centreFragment = CenterFragment.newInstance();
        flowFragment = FlowFragment.newInstance();
        outAndInFragment = OutAndInFragment.newInstance(this);
//        apnFragment = ApnFragment.newInstance();
        beidouFragment = BeidouFragment.newInstance();
        ethernetFragment = EthernetFragment.newInstance();
//        loraFragment = LoraFragment.newInstance();
        cameraFragment = CameraFragment.newInstance();
        passagewayFragment = PassagewayFragment.newInstance();
        smsFragment = SMSFragment.newInstance();
        mTabEntities = new ArrayList<>();
    }


    @Override
    protected void onResume() {
        super.onResume();
//        getImmersionBar().statusBarDarkFont(true,0.5f);
        getImmersionBar().statusBarDarkFont(true).init();
        isFront = true;
    }


    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTabEntities.get(position).getTabTitle();
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }


    public class TabEntity implements CustomTabEntity {
        public String title;
        public int selectedIcon;
        public int unSelectedIcon;

        public TabEntity(String title, int selectedIcon, int unSelectedIcon) {
            this.title = title;
            this.selectedIcon = selectedIcon;
            this.unSelectedIcon = unSelectedIcon;
        }

        @Override
        public String getTabTitle() {
            return title;
        }

        @Override
        public int getTabSelectedIcon() {
            return selectedIcon;
        }

        @Override
        public int getTabUnselectedIcon() {
            return unSelectedIcon;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {//选择文件返回
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 69:
                    Uri uri = data.getData();
//                     chooseFilePath=FileChooseUtil.getInstance(this).getChooseFileResultPath(uri);
//                    Log.d(TAG,"选择文件返回："+chooseFilePath);
//                    sendFileMessage(chooseFilePath);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        BleUtils.stopNotify();
        BleUtils.stopDownTimer();
        super.onDestroy();
    }

    private boolean isFront = false;

    @Override
    protected void onPause() {
        super.onPause();
        isFront = false;
    }

    @Override
    public void onMessageEvent(PopHandleMessage event) {
        super.onMessageEvent(event);
        BleLog.d("onDisConnected =PopHandleMessage==" + event.message);
        if (isFront) {
            BleUtils.reConnect(mContext, new BleUtils.BleUtilLoginCallBack() {
                @Override
                public void isLogin(boolean isSuccess, String message) {
                    showToast("" + message);
                    dismissProgress();
                }
            });
        }
    }
}



